<template>
    <div>
        <div class="cameraBox">
            <video src="" autoplay id="videoCamera" class="videoCamera" :width="videoWidth" :height="videoHeight">

            </video>

            <canvas id="canvasCamera" class="canvasCamera" :width="videoWidth" :height="videoHeight">

            </canvas>
            <div>
                <el-button @click="photograph"> 拍照</el-button>
                <!-- 默认状态  切换到当前组件摄像头打开  -->
                <el-button v-if="flag" @click="openCamera"> 打开摄像头</el-button>
                <el-button v-else @click="closeCamera"> 关闭摄像头</el-button>
                <el-button @click="resetPhoto"> 重置</el-button>
                <el-button @click="goStuInfoEntry"> 提交</el-button>
            </div>

        </div>


    </div>
</template>

<script>
export default {
    data() {
        return {
            flag: false,
            videoWidth: 500,
            videoHeight: 400,
            thisVideo: null,
            thisContext: null,
            thisCanvas:"",
            imgSrc:"",


        }
    },
    mounted() {
        this.openCamera();
    },
    methods: {

        //重置按钮 作用：清除画布当中的照片，重新照照片
        resetPhoto() {
            //前提是先拍照后清空
            // console.log(this.thisCanvas);
            // console.log(this.thisContext);

            this.thisCanvas = document.querySelector(".canvasCamera");
            this.thisContext = this.thisCanvas.getContext("2d");

            //先清空
            this.thisContext.clearRect(0, 0, this.videoWidth, this.videoHeight);

        },

        //提交按钮 作用：将this.imgSrc传递给学生信息录入组件   即跳转到学生信息录入组件
        goStuInfoEntry() {
            console.log(this.imgSrc);
            this.$router.push({
                name: 'StuInfoEntry',
                query: {
                    imgSrc: this.imgSrc
                }
            })
        },

        //拍照
        //拍照实际上就是将video当中播放的某个瞬间 用画图的方式  画到canvas中
        photograph() {
            //获取画布
            this.thisCanvas = document.querySelector('.canvasCamera');
            //获取画笔
            this.thisContext = this.thisCanvas.getContext("2d");
            this.thisContext.drawImage(
                this.thisVideo,
                0,
                0,
                50,
                50,

            );
            this.imgSrc = this.thisCanvas.toDataURL('img/png', 0.1);
            // console.log(this.imgSrc);

        },

        //打开摄像头头
        openCamera() {
            this.flag = false;
            this.thisVideo = document.getElementById("videoCamera")       //打开摄像头权限的方法   navigator.mediaDevices.getUserMedia
            //注意旧版本浏览器可能不支持mediaDevices  如果不支持，那我们就将navigator.mediaDevices 设置为一个空对象
            if (navigator.mediaDevices === undefined) {
                navigator.mediaDevices = {}
            }
            //有些浏览器的 getUserMedia    某些浏览器他会覆盖该属性
            if (navigator.mediaDevices.getUserMedia === undefined) {
                navigator.mediaDevices.getUserMedia = function (constraints) {
                    //获取不同浏览器的getUserMedia
                    let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
                    //如果在这些浏览器之外 还是没有getUserMedia,告诉他门 请更换浏览器
                    if (!getUserMedia) {
                        return Promise.reject(
                            new Error('请更换浏览器')
                        )

                    }


                    //如果有getuserMedia  （在不同内核有） 将其给navigator
                    return new Promise((resolve, reject) => {
                        getUserMedia.call(navigator, constraints, resolve, reject)
                    })

                }
            }
            //传入音视频信息
            const constraints = {
                audio: false,
                video: {
                    width: this.videoWidth,
                    height: this.videoHeight,
                }
            };
            //调用摄像头
            navigator.mediaDevices.getUserMedia(constraints)
                .then((res) => {
                    console.log(res);
                    console.log(this.thisVideo);
                    if ("srcObject" in this.thisVideo) {
                        this.thisVideo.srcObject = res
                    } else {
                        //windo.URL.createObjectURL  创建一个新对象  URL
                        this.thisVideo.src = window.URL.createObjectURL(res);

                    }

                    this.thisVideo.onloadedmetaate = function () {
                        console.log("视频源数据加载完毕");
                        console.log(this);
                        this.play()
                    }


                })
                .catch((err) => {
                    console.log(err);
                    this.$message({
                        message: "没有开启摄像头或者浏览器不支持请求更换浏览器",
                        type: "warning",
                    });
                });

        },

        //关闭摄像头
        closeCamera() {
            if (this.thisVideo && this.thisVideo !== null) {
                this.thisVideo.srcObject.getTracks()[0].stop();
                this.flag = true;
            }
        },

    },

};
</script>

<style lang="scss" scoped>

div {
  .videoCamera {
    margin-right: 10px;
  }
}

</style>